﻿
CREATE PROCEDURE [dbo].[CustomerReturnLinesUpdate]
(--возврат от покупателя
	@Qntty int,
	@RetailSum decimal(19, 2),
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE	@orgDocId int, @orgPartyId int, @orgDocDate smalldatetime
DECLARE	@orgReturnLineId int, @orgQntty int, @intReturnQntty int, @intAlreadyQntty int

DECLARE @intInputCount int, @intOutputCount int

SET NOCOUNT ON
IF (@Qntty Is Null) OR (@RetailSum Is Null) OR (@Original_Id Is Null) OR (@Original_MD Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <=0) OR (@RetailSum <=0)
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Количество и сумма д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgDocId = L.DocId, @orgPartyId = L.PartyId, 
@orgReturnLineId = L.ReturnLineId, @orgQntty = L.Qntty,
@orgDocDate = D.DocDate
FROM CA.GoodsDocLines L INNER JOIN CA.Documents AS D ON L.DocId = D.Id
WHERE L.Id = @Original_Id AND L.MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intReturnQntty = Qntty FROM CA.GoodsDocLines WHERE Id = @orgReturnLineId

SELECT @intAlreadyQntty = sum(L.Qntty) --уже возвращено
FROM CA.GoodsDocLines AS L INNER JOIN CA.Documents AS D ON L.DocId = D.Id
WHERE D.DocTypeId = 7 AND L.ReturnLineId = @orgReturnLineId

IF (@Qntty - @orgQntty + IsNull(@intAlreadyQntty, 0))> @intReturnQntty
BEGIN
	SELECT @intErrCode = 4, 
	@strMsg = 'Возвращенное количество больше проданного количества!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty - @orgQntty ) < 0 --уменьшение количества по возврату
BEGIN --проверка товародвижения
	SET @orgQntty = @Qntty - @orgQntty
	EXEC @intRet = dbo.CheckPartyFlow @orgPartyId, @orgQntty, @orgDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
	IF @intRet <> 0 RETURN @intRet
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

	SET NOCOUNT OFF;
UPDATE [CA].[GoodsDocLines] SET 
[Qntty] = @Qntty, 
[RetailSum] = @RetailSum, 
[MD] = @MD, [MW] = @MW, Note = @Note
WHERE Id = @Original_Id;

SELECT L.Id, L.DocId, L.PartyId, 
L.Qntty, L.RetailSum, L.ReturnLineId,
L.Note, L.MD, L.MW 
FROM CA.GoodsDocLines AS L WHERE L.Id = @Original_Id
RETURN 0
